<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 会员管理
 * Class Member
 */
class Model_Member extends ORM
{
    protected $_primary_key = 'mid';

    public static $equity_style_img = [
        1 => '/uploads/equity/style/style_1.png',
        2 => '/uploads/equity/style/style_2.png',
        3 => '/uploads/equity/style/style_3.png',
        4 => '/uploads/equity/style/style_4.png',
        5 => '/uploads/equity/style/style_5.png',
        6 => '/uploads/equity/style/style_6.png',
        7 => '/uploads/equity/style/style_7.png',
        8 => '/uploads/equity/style/style_8.png',
    ];

    /**
     * @function 根据mid获取会员信息
     * @param $memberid
     * @return mixed
     */
    public static function get_member_info($memberid)
    {
        $fields = array(
            'mid',
            'mtype',
            'nickname',
            'truename',
            'sex',
            'rank',
            'money',
            'email',
            'mobile',
            'jifen',
            'litpic',
            'jointime',
            'joinip',
            'logintime',
            'loginip',
            'province',
            'city',
            'cardid',
            'address',
            'regtype',
            'qq',
            'verifystatus',
            'wechat',
            'reg_from',
            'reg_time',
            'money_frozen'
        );
        $result = DB::select_array($fields)->from('member')->where('mid', '=', $memberid)->execute()->current();
        return $result;
    }

    /**
     * @function 获取默认会员头像
     * @return string
     */
    public static function member_nopic()
    {
        return $GLOBALS['cfg_public_url'] . 'images/member_nopic.png';
    }

    /**
     * @param $memberId
     * @param $param
     * @return array|int|mixed|string
     * @throws Kohana_Exception
     * 获取会员等级信息
     */
    public static function member_rank($member_id, $param = array())
    {
        //等级计算规则 1积分累计 2积分余额 3总充值金额
        $grade_rule = Model_Sysconfig::get_configs(0, 'cfg_member_grade_rule', 1);
        //等级列表
        $rank = self::member_grade($grade_rule);
        if (!empty($member_id)) {
            $member_discount = false;
            //当前会员等级信息
            $member_info = DB::select('grade_id', 'grade_name', 'grade_expire_time', 'cardid', 'jifen', 'birth_date', 'jifen_lottery_num')
                ->from('member')->where('mid', '=', $member_id)->execute()->current();
            //等级计算规则 1按累计金额计算 2按余额计算
            if ($grade_rule == 1) {
                //会员历史获得积分总额
                $jifen = DB::select(DB::expr("sum(jifen) as cumulative_jifen"))->from('member_jifen_log')
                    ->where('type', '=', 2)
                    ->and_where('memberid', '=', $member_id)
                    ->and_where(DB::expr(" and content not like '%退还%' "))
                    ->execute()->get('cumulative_jifen');
            } else {
                //会员积分余额
                $jifen = DB::select()->from('member')->where('mid', '=', $member_id)->execute()->get('jifen');
            }

            //当前等级信息
            $next          = [];
            $current_grade = [];
            $range         = array();
            foreach ($rank as $k => &$v) {
                //已有等级id且等级还未过期时，获取对应等级的key
                if ($member_info['grade_id'] && $v['id'] == $member_info['grade_id']) {
                    $current_grade            = $v;
                    $current_grade['current'] = $k + 1;
                    $next                     = $rank[$k + 1] ?: [];
                    if ($next) {
                        $next['current'] = $k + 2;
                    }
                }
                if ($grade_rule != 3) {
                    $range[] = $v['begin'];
                } else {
                    $range[] = $v['price'];
                }
            }

            if ($grade_rule != 3) {
                //按积分算的新等级
                $k                    = self::getI($range, $jifen, 0);
                $new_grade            = $rank[$k];
                $new_grade['current'] = ++$k;
            } else {
                //按充值金额计算新等级
                $amount               = DB::select()->from('wallet_member')->where('member_id', '=', $member_id)->execute()->get('amount');
                $k                    = self::get_key($range, $amount);
                $new_grade            = $rank[$k];
                $new_grade['current'] = ++$k;
            }


            //当前等级高于新等级且等级还未过期时，等级还是以当前等级为准
            if ($current_grade['current'] >= $new_grade['current'] && ($member_info['grade_expire_time'] > time() || $member_info['grade_expire_time'] == 0)) {
                $grade = $current_grade;
            } else {
                $grade = $new_grade;
                $next  = $rank[$k] ?: [];
                if ($next) {
                    $next['current'] = ++$k;
                }
            }
            if (isset($next['grade_rules'])) {
                if ($next['grade_rules'] == 1) {
                    $next['diff_info'] = '升级LV' . $next['current'] . '还需' . bcsub($next['end'], $jifen) . '积分';
                    $percentage        = bcmul(bcdiv($jifen, $next['end'], 2), 100) . '%';//离下一个等级的进度
                } else {
                    $next['diff_info'] = '升级LV' . $next['current'] . '需累计充值' . $next['price'] . '元';
                    $percentage        = bcmul(bcdiv($amount, $next['price'], 2), 100) . '%';//离下一个等级的进度
                }
            } else {
                $next['diff_info'] = '查看权益';
                $percentage        = '100%';
            }


            //处理等级变更时的赠送信息
            $equity   = Model_Member_Grade::get_equity($grade['id']);
            if (in_array(2, $equity['equity_id'])) {
                $member_discount = true;
            }
            $params = [
                'member_id'     => $member_id,
                'new_grade'     => $new_grade,
                'current_grade' => $current_grade,
                'member_info'   => $member_info,
                'jifen'         => $jifen,
                'equity'        => $equity,
            ];
            Model_Member_Grade::grade_change_handler($params);
        } else {
            $grade_id = $param['vr_grade'];
            foreach ($rank as $key => $g) {
                if ($grade_id == $g['id']) {
                    $grade            = $g;
                    $grade['current'] = $key + 1;
                    break;
                }
            }
        }

        //组合返回数据
        $data = array();
        if (isset($param['return'])) {
            switch ($param['return']) {
                case 'current':
                    $data = 'LV'.$grade['current'];
                    break;
                case 'rankname':
                    $data = $grade['name'];
                    break;
                default:
                    $data = array(
                        'grade'           => $rank, //各等级详细信息
                        'jifen'           => $jifen, //剩余积分或累计积分
                        'current'         => $grade['current'], //当前等级
                        'rankname'        => $grade['name'], //当前等级
                        'current_rank'    => $grade, //当前等级详细信息
                        'range'           => $range, //积分区间
                        'total'           => count($rank), //共多少个等级
                        'next'            => $next, //下一个等级
                        'percentage'      => $percentage, //百分比
                        'member_discount' => $member_discount,//当前等级是否支持会员折扣
                    );
            }
        }
        return $data;
    }

    public static function get_member_rank($member_id, $param = array())
    {
        //等级计算规则 1积分累计 2积分余额 3总充值金额
        $grade_rule = Model_Sysconfig::get_configs(0, 'cfg_member_grade_rule', 1);
        //等级列表
        $rank = self::member_grade($grade_rule);
        if (!empty($member_id)) {
            $member_discount = false;
            //当前会员等级信息
            $member_info = DB::select('grade_id', 'grade_name', 'grade_expire_time', 'cardid', 'jifen', 'birth_date', 'jifen_lottery_num')
                ->from('member')->where('mid', '=', $member_id)->execute()->current();
            //等级计算规则 1按累计金额计算 2按余额计算
            if ($grade_rule == 1) {
                //会员历史获得积分总额
                $jifen = DB::select(DB::expr("sum(jifen) as cumulative_jifen"))->from('member_jifen_log')
                    ->where('type', '=', 2)
                    ->and_where('memberid', '=', $member_id)
                    ->and_where(DB::expr(" and content not like '%退还%' "))
                    ->execute()->get('cumulative_jifen');
            } else {
                //会员积分余额
                $jifen = DB::select()->from('member')->where('mid', '=', $member_id)->execute()->get('jifen');
            }

            //当前等级信息
            $next          = [];
            $current_grade = [];
            $range         = array();
            foreach ($rank as $k => &$v) {
                //已有等级id且等级还未过期时，获取对应等级的key
                if ($member_info['grade_id'] && $v['id'] == $member_info['grade_id']) {
                    $current_grade            = $v;
                    $current_grade['current'] = $k + 1;
                    $next                     = $rank[$k + 1] ?: [];
                    if ($next) {
                        $next['current'] = $k + 2;
                    }
                }
                if ($grade_rule != 3) {
                    $range[] = $v['begin'];
                } else {
                    $range[] = $v['price'];
                }
            }

            if ($grade_rule != 3) {
                //按积分算的新等级
                $k                    = self::getI($range, $jifen, 0);
                $new_grade            = $rank[$k];
                $new_grade['current'] = ++$k;
            } else {
                //按充值金额计算新等级
                $amount               = DB::select()->from('wallet_member')->where('member_id', '=', $member_id)->execute()->get('amount');
                $k                    = self::get_key($range, $amount);
                $new_grade            = $rank[$k];
                $new_grade['current'] = ++$k;
            }


            //当前等级高于新等级且等级还未过期时，等级还是以当前等级为准
            if ($current_grade['current'] >= $new_grade['current'] && ($member_info['grade_expire_time'] > time() || $member_info['grade_expire_time'] == 0)) {
                $grade = $current_grade;
            } else {
                $grade = $new_grade;
                $next  = $rank[$k] ?: [];
                if ($next) {
                    $next['current'] = ++$k;
                }
            }
            if (isset($next['grade_rules'])) {
                if ($next['grade_rules'] == 1) {
                    $next['diff_info'] = '升级LV' . $next['current'] . '还需' . bcsub($next['end'], $jifen) . '积分';
                    $percentage        = bcmul(bcdiv($jifen, $next['end'], 2), 100) . '%';//离下一个等级的进度
                } else {
                    $next['diff_info'] = '升级LV' . $next['current'] . '需累计充值' . $next['price'] . '元';
                    $percentage        = bcmul(bcdiv($amount, $next['price'], 2), 100) . '%';//离下一个等级的进度
                }
            } else {
                $next['diff_info'] = '查看权益';
                $percentage        = '100%';
            }

        } else {
            $grade_id = $param['vr_grade'];
            foreach ($rank as $key => $g) {
                if ($grade_id == $g['id']) {
                    $grade            = $g;
                    $grade['current'] = $key + 1;
                    break;
                }
            }
        }

        //组合返回数据
        $data = array();
        if (isset($param['return'])) {
            switch ($param['return']) {
                case 'current':
                    $data = 'LV'.$grade['current'];
                    break;
                case 'rankname':
                    $data = $grade['name'];
                    break;
                default:
                    $data = array(
                        'grade'           => $rank, //各等级详细信息
                        'jifen'           => $jifen, //剩余积分或累计积分
                        'current'         => $grade['current'], //当前等级
                        'rankname'        => $grade['name'], //当前等级
                        'current_rank'    => $grade, //当前等级详细信息
                        'range'           => $range, //积分区间
                        'total'           => count($rank), //共多少个等级
                        'next'            => $next, //下一个等级
                        'percentage'      => $percentage, //百分比
                        'member_discount' => $member_discount,//当前等级是否支持会员折扣
                    );
            }
        }
        return $data;
    }

    /**
     * @param $range
     * @param $amount
     * @return int|string
     * 通过充值总金额获取对应等级的key
     */
    public static function get_key($range,$amount)
    {
        $key = 0;
        if($amount>0){
            foreach ($range as $k => $price) {
                if($price <= $amount && $k>$key){
                    $key = $k;
                }
            }
        }
        return $key;
    }

    /**
     * 获取会员所在等级
     * @param $member_id
     * @return false|mixed
     */
    public static function get_member_grade($member_id)
    {
        $rank = self::member_grade();
        if($rank) {
            $k = 0;

            //当前会员等级信息
            $member_grade = DB::select('grade_id', 'grade_name', 'grade_expire_time')
                ->from('member')->where('mid', '=', $member_id)->execute()->current();

            //等级计算规则 1按累计金额计算 2按余额计算
            $grade_rule = Model_Sysconfig::get_configs(0, 'cfg_member_grade_rule', 1);
            if ($grade_rule == 1) {
                //会员历史获得积分总额
                $jifen = DB::select(DB::expr("sum(jifen) as cumulative_jifen"))->from('member_jifen_log')
                    ->where('type', '=', 2)
                    ->and_where('memberid', '=', $member_id)
                    ->and_where(DB::expr(" and content not like '%退还%' "))
                    ->execute()->get('cumulative_jifen');
            } else {
                //会员积分余额
                $jifen = DB::select()->from('member')->where('mid', '=', $member_id)->execute()->get('jifen');
            }

            $range = array();
            foreach ($rank as $k => $v) {
                if ($v['id'] == $member_grade['grade_id']) {
                    $key = $k;
                }
                //只要区间升级类型的数据
                if($v['grade_rules'] == 1) {
                    $range[] = $v['begin'];
                }
            }
            if ($key || $key === 0) {
                $k = $key;
            } else {
                $k = self::getI($range, $jifen, $k);
            }

            $grade = $rank[$k];
        }else{
            $grade = false;
        }
        return $grade;
    }

    /**
     * @function 会员等级规则
     * @return mixed
     */
    public static function member_grade($grade_rule='all')
    {
        static $grade = null;
        if (is_null($grade))
        {
            if($grade_rule){
                $grade_rule = DB::select()->from('sysconfig')->where('varname', '=', 'cfg_member_grade_rule')->execute()->get('value');
            }
			if($grade_rule=='all'){
				$grade = DB::select()->from('member_grade')
                    ->and_where('end','>',0)
                    ->order_by('begin', 'asc')
                    ->execute()->as_array();
			}else if($grade_rule==3){
                $grade = DB::select()->from('member_grade')
                    ->where("grade_rules=2 and (is_system=1 or price>0)")
                    ->order_by('price', 'asc')
                    ->execute()->as_array();
            }else{
                $grade = DB::select()->from('member_grade')
                    ->where('grade_rules','=',1)
                    ->and_where('end','>',0)
                    ->order_by('begin', 'asc')
                    ->execute()->as_array();
            }
        }
        return $grade;
    }

    ///************************ PC端开始   **********************////


    /**
     * @function 新增注册用户
     * @param $data
     * @return object|string
     * @throws Kohana_Exception
     */
    public static function register($data)
    {
        //数据验证
        //检查账号
        $user = isset($data['mobile']) ? $data['mobile'] : $data['email'];
        $user = self::member_find($user);
        if (!empty($user))
        {
            return __('error_member_exists');
        }
        //添加
        $result = DB::insert('member', array_keys($data))->values(array_values($data))->execute();
        return $result[1] > 0 ? $result : __('error_member_insert');
    }

    /**
     * @function 登录
     * @param $loginname
     * @param $loginpwd
     * @param $hasencode 密码是否已加密
     */
    public static function login($loginname, $loginpwd, $hasencode)
    {

        $user = self::member_find($loginname, $loginpwd, $hasencode);
        /*if ($user)
        {
            $serectkey = Common::authcode($user['mid'] . '||' . $user['pwd'], '');
            //写登录信息
            self::write_cookie('st_username', $user['nickname']);
            self::write_cookie('st_userid', $user['mid']);
            self::write_cookie('st_secret', $serectkey);
            self::save_login_time($user['mid']);

        }*/
        return $user;
    }

    /**
     * @function 退出登录
     */
    public static function login_out()
    {
        Model_Member_Login::login_out();
    }

    /**
     * @function 保存登录时间
     * @param $mid
     */
    public static function save_login_time($mid)
    {
        $m = ORM::factory('member', $mid);
        $now = time();
        $jifen = Model_Jifen::reward_jifen('sys_member_login',$mid);
        if ($jifen)
        {
            $content = "登录获得{$jifen}积分";
            St_Product::add_jifen_log($mid, $content,$jifen, 2);
        }
        $m->logintime = $now;
        $m->save();

    }


    /**
     * @function 查找用户
     * @param $user
     * @param null $pwd
     * @param string $hasencode
     * @return mixed
     */
    public static function member_find($user, $pwd = null, $hasencode = '')
    {
        $userType = strpos($user, '@') ? 'email' : 'mobile';
        if (!is_null($pwd))
        {
            $pwd = $hasencode ? $pwd : md5($pwd);
        }
        $obj = DB::select()->from('member')->where($userType, '=', $user);
        if ($pwd)
        {
            $obj = $obj->and_where('pwd', '=', $pwd);
        }
        $result = $obj->execute()->current();
        return $result;
    }

    /**
     * @function 根据会员id获取用户信息
     * @param $mid
     * @return array
     */
    public static function get_member_byid($mid)
    {
        if ($mid)
        {
            $memberinfo = DB::select()->from('member')->where('mid', '=', $mid)->execute()->current();
            if (empty($memberinfo['mid']))
            {
                return array();
            }
            $memberinfo['last_logintime'] = Common::mydate('Y-m-d', $memberinfo['logintime']);
            $memberinfo['litpic'] = !empty($memberinfo['litpic']) ? $memberinfo['litpic'] : self::member_nopic();
            //第三方登录
            $third = DB::select()->from('member_third')->where("mid={$mid}")->execute()->as_array();
            $memberinfo['third'] = Model_Member_Third::thirdData($third);

            if (St_Functions::is_normal_app_install('system_wallet')) {
                $wallet_member = DB::select()->from('wallet_member')->where('member_id', '=', $mid)->execute()->current();
                $memberinfo['wallet_balance'] = $wallet_member['remain_amount']?:0;
                $memberinfo['total_balance']  = bcadd($memberinfo['money'], $memberinfo['wallet_balance'], 2);
            }

            return $memberinfo;
        }

    }

    /**
     * @function 积分处理
     * @param $mid
     * @param $jifen 积分
     * @param int $type 1：使用 2：获取
     * @return object
     */
    public static function operate_jifen($mid, $jifen, $type = 1)
    {
        if (empty($jifen))
        {
            return;
        }
        $jifen = $type == 1 ? -$jifen : $jifen;
        $sql = "UPDATE sline_member SET jifen=jifen+({$jifen}) ";
        $sql .= "WHERE mid={$mid}";
        $row = DB::query(Database::UPDATE, $sql)->execute();
        return $row;
    }

    /**
     * @function 写cookie
     * @param $key
     * @param $value
     */
    public static function write_cookie($key, $value)
    {
        Cookie::set($key, $value, 7200);
    }


    /**
     * @function 判断会员是否存在
     * @param $loginname
     * @return bool
     */
    public static function check_member_exist($loginname)
    {
        $field='mobile';
        if (strpos($loginname, '@'))
        {
           // $where = "email='{$loginname}'";
            $field='email';
        }

        $result = DB::select()->from('member')->where($field,'=',$loginname)->execute()->as_array();
        $flag = false;
        if (!empty($result))
        {
            $flag = true;
        }
        return $flag;
    }

    /**
     * @function 检测是否登录
     * @return array
     * @throws Kohana_Exception
     */
    public static function check_login()
    {
//        $user = array();
//        $secret = Cookie::get('st_secret');
//        if (!empty($secret))
//        {
//            $info = explode('||', Common::authcode($secret));
//            if (isset($info[0]) && $info[1])
//            {
//                $mid = Common::remove_xss($info[0]);
//                $upwd = Common::remove_xss($info[1]);
//
//                $model = ORM::factory('member')->where("mid='{$mid}' and pwd='{$upwd}'")->find();
//                if (isset($model->mid))
//                {
//                    $user = $model->as_array();
//                }
//            }
//        }
        //同步更新老判断方法
        $user=Model_Member_Login::check_login_info();
        return $user;
    }
    ///************************ PC端结束   *********************///

    ///*******************手机端开始  **********************///

    /**
     * @param 写入session
     * @param $member 会员详细信息
     * @param $user 登录账号手机或邮箱
     */
    public static function write_session($member, $user = null)
    {
        if (is_null($user))
        {
            $user = empty($member['email']) ? $member['mobile'] : $member['email'];
        }
        //昵称
        if (empty($member['nickname']) && !empty($user))
        {
            $member['nickname'] = substr_replace($user, '****', floor(strlen($user) / 2) - 2, 4);
        }
        //没有会员图片
        if (empty($member['litpic']))
        {
            $member['litpic'] = self::member_nopic();
        }
        //登录信息写入seesion
        Common::session('member', array('mid' => $member['mid'], 'nickname' => $member['nickname'], 'litpic' => $member['litpic']));
        self::write_member_cookie($member);
    }

    public static function write_member_cookie($user)
    {

        if ($user)
        {
            $serectkey =Common::authcode($user['mid'] . '||' . $user['pwd'], '');
            //写登录信息
            self::write_cookie('st_username', $user['nickname']);
            self::write_cookie('st_userid', $user['mid']);
            self::write_cookie('st_secret', $serectkey);
            self::save_login_time($user['mid']);

        }
        return $user;
    }

    ///*******************手机端结束  **********************///


    ///********************后台开始    **********************///
    /*
     * 检查是否存在相同数据
     * */
    public static function checkExist($field, $value, $mid = '')
    {
        $flag = 'true';

        $query = DB::select('mid')->from('member')->where($field, '=', $value);
        // $model = ORM::factory('member')->where($field,'=',$value);
        if (!empty($mid))
        {
            $query->and_where('mid', '!=', $mid);
        }
        else
        {

        }
        $result = $query->execute()->current();
        if ($result['mid'])
        {
            $flag = 'false';
        }
        return $flag;
    }

    //获取消费总额
    public static function get_consume_amount($mid)
    {
        $orderList = DB::query(Database::SELECT, "select * from sline_member_order where memberid='$mid' and (status=2 or status=5)")->execute()->as_array();
        $amount = 0;
        foreach ($orderList as $row)
        {
            $amount += Model_Member_Order::get_payed_amount($row);
        }
        return $amount;
    }



    ///********************后台结束   **********************///

    /**
     * @function 会员钱包交易操作
     * @param $mid 会员ID
     * @param $amount 交易金额
     * @param $type 交易类型 0-收入, 1-支出, 2-冻结,3-解冻
     * @param $description  日志描述
     * @param bool $isFrozen 是否已冻结过资金，仅当$type=1时有效
     * @param string $orderid 订单id,可选
     * @param string $withdrawid 提现id,可选
     * @param bool $isThrowException 若操作失败是否将异常抛出
     * @return array  //status项表示成功或失败，status为false时，还会有msg项，表示错误原因
     * @throws Kohana_Exception
     */
    public static function cash_deal($mid,$amount,$type,$description,$isFrozen=false,$orderid='',$withdrawid='',$isThrowException=false)
    {
        $amount = doubleval($amount);
        $member_model = ORM::factory('member',$mid);
        $db = Database::instance();
        $db->begin();
        try
        {
            if(!$member_model->loaded())
            {
                throw new Exception('会员不存在');
            }
            if($amount<=0)
            {
                throw new Exception('交易额不得小于0');
            }
            $money = doubleval($member_model->money);
            $money_frozen = doubleval($member_model->money_frozen);
            //如果是收入
            if($type==0)
            {
                $member_model->money+=$amount;
                $member_model->save();
                if(!$member_model->saved())
                {
                    throw new Exception('保存失败');
                }
            }
            //如果是支出
            if($type==1)
            {
                if($isFrozen)
                {
                    if($amount>$money_frozen)
                    {
                        throw new Exception('支出金额大于冻结金额');
                    }
                    if($amount>$money)
                    {
                        throw new Exception('支出金额大于总金额');
                    }

                }
                else if($amount>$money)
                {
                    throw new Exception('支出金额大于总金额');
                }

                $member_model->money-=$amount;
                if($isFrozen)
                {
                    $member_model->money_frozen-=$amount;
                }
                $member_model->save();
                if(!$member_model->saved())
                {
                    throw new Exception('保存失败');
                }

            }
            //如果是冻结
            if($type==2)
            {
                if($amount>($money-$money_frozen))
                {
                    throw new Exception('冻结金额大于可用金额');
                }
                $member_model->money_frozen+=$amount;
                $member_model->save();
                if(!$member_model->saved())
                {
                    throw new Exception('保存失败');
                }
            }
            //如果是解冻
            if($type==3)
            {
                if($amount>$money_frozen)
                {
                    throw new Exception('解冻金额大于冻结金额');
                }
                $member_model->money_frozen-=$amount;
                $member_model->save();
                if(!$member_model->saved())
                {
                    throw new Exception('保存失败');
                }
            }
            $log_result = Model_Member_Cash_Log::add_log($mid,$type,$amount,$description,array('orderid'=>$orderid,'withdrawid'=>$withdrawid));
            if(!$log_result)
            {
                throw new Exception('保存日志失败');
            }
            $db->commit();
            return array('status'=>true);
        }
        catch (Exception $e)
        {
            $db->rollback();
            if($isThrowException)
            {
                throw $e;
            }
            else
            {
                return array('status' => false, 'msg' => $e->getMessage());
            }
        }
    }

	//支付模块移动过来的函数

	    /**
     * 获取模型拼音标识
     * @param $id
     * @return mixed
     */
    static function email_by_id($id)
    {
        $sql = "select email from sline_member where mid={$id}";
        $arr=DB::query(Database::SELECT, $sql)->execute()->current();
        return $arr['email'];
    }

    /**
     * @param array $range
     * @param $jifen
     * @param int $k
     * @return int|string
     */
    public static function getI(array $range, $jifen, int $k)
    {
        $rangeLevel = count($range);
        if ($jifen < $range[0]) {
            $k = 0;
        } else if ($jifen > $range[$rangeLevel - 1]) {
            $k = $rangeLevel - 1;
        } else {
            foreach ($range as $k => $v) {
                if ($jifen < $v) {
                    --$k;
                    break;
                }
            }
        }
        return $k;
    }

    public function delete_clear()
    {
       $fenxiao_result= DB::query(Database::SELECT,"show tables like 'sline_fenxiao'")->execute()->as_array();
       if(!empty($fenxiao_result[0]))
       {
          DB::delete('fenxiao')->where('memberid','=',$this->mid)->execute();
       }
       $this->delete();

       //清除第三方登录会员
        DB::delete('member_third')->where('mid','=',$this->mid)->execute();

    }

    public static $_reg_from_arr = array(
        0 => '管理员添加',
        1 => 'PC端',
        2 => '手机端',
        3 => '微信端',
        4 => '小程序',
        5 =>'QQ',
        6=>'微博'
    );

    /**
     * 新增:注册后回调,更新注册来源和注册时间
     * @param $id
     * @return mixed
     */
    public static function add_reg_from($mid,$from=null)
    {
        if(!$mid)
        {
            return;
        }
        $mid = intval($mid);
        $user = self::get_member_info($mid);
        if($user)
        {
            DB::update('member')->set(array('reg_from'=>$from,'reg_time'=>time()))
                ->where('mid','=',$mid)
                ->execute();
        }
    }

    public static function member_reg_from($from=null)
    {
        if(is_null($from))
        {
            $where = '未知';
        }
        else
        {
            $from = intval($from);
            $where = self::$_reg_from_arr[$from];
        }
        return $where;
    }

    public static function get_member_third($userid)
    {
        $result = DB::select('openid')->from('member_third')->where("mid",'=',$userid)->execute()->current();
        return $result;
    }

    /**
     * @function 根据手机号自动注册账号
     * @param $mobile
     * @return int|mixed
     */
    public static function auto_reg($mobile,$reg_arr=null)
    {
        $out = 0;
        $sql = "SELECT mid FROM `sline_member` WHERE mobile='$mobile'";
        $row = DB::query(1, $sql)->execute()->as_array();
        if (!empty($row[0]['mid']))
        {
            $out = $row[0]['mid'];
        }
        else
        {
            $pwd = md5($mobile);
            $jointime = time();
            $joinip = St_Functions::get_ip();
            //  $jifen = empty($GLOBALS['cfg_reg_jifen']) ? 0 : $GLOBALS['cfg_reg_jifen'];//网上注册赠送积分
            $nickname = !empty($reg_arr) ? $reg_arr['nickname'] : substr($mobile, 0, 5) . '***';
            $m = ORM::factory('member');
            $member = array(
                'nickname' => $nickname,
                'pwd' => $pwd,
                'jointime' => $jointime,
                'logintime' => $jointime,
                'email' => '',
                'mobile' => $mobile,
                'joinip' => $joinip,
                'jifen' => 0,
                'litpic' => !empty($reg_arr) ? $reg_arr['litpic'] : ''
            );
            foreach ($member as $key => $value)
            {
                $m->$key = $value;
            }
            $m->save();
            if ($m->saved())
            {
                $out = $m->mid;
                $jifen = Model_Jifen::reward_jifen('sys_member_register', $m->mid);
                if (!empty($jifen))
                {
                    St_Product::add_jifen_log($m->mid, "注册赠送积分{$jifen}", $jifen, 2);
                }
                Plugin_Core_Factory::factory()->add_listener('on_member_register', $m->as_array())->execute();
                St_SMSService::send_member_msg($mobile, NoticeCommon::MEMBER_REG_MSGTAG, $mobile, $mobile, '');
            }
        }
        return $out;
    }

    // 生成密码
    public static function make_pwd($pwd): string
    {
        return md5($pwd);
    }
}